package org.shark.jdbcTemplateTool.dao;

import com.shark.app.common.exception.DataAccessException;
import com.shark.app.common.utils.SpringUtil;
import org.shark.jdbcTemplateTool.JdbcTemplateTool;
import org.shark.jdbcTemplateTool.exception.NoColumnAnnotationFoundException;
import org.shark.jdbcTemplateTool.exception.NoIdAnnotationFoundException;
import org.shark.jdbcTemplateTool.model.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by xiaojun on 16/8/25.
 */
public class BasedaoUtil {

    private static Logger log = LoggerFactory.getLogger(BasedaoUtil.class);

    protected final static JdbcTemplateTool jtt = SpringUtil.getBean(JdbcTemplateTool.class);

    /**
     * 根据ID取得数据
     * @param id
     * @return
     */
    public static Object get(Class<?> entityClass, Object id) {
        try {
            return jtt.get(entityClass, id);
        } catch (NoIdAnnotationFoundException | NoColumnAnnotationFoundException e) {
            log.error("Entity 错误。" + entityClass.getName(), e);
        }
        return null;
    }

    public static Page page(Class<?> entityClass, String sql, Object[] params, int currentPage, int pagesize) {
        return jtt.page(sql, params, currentPage, pagesize, entityClass);
    }

    /**
     * 更新数据
     * @param po
     * @return
     */
    public static int update(Object po) {
        try {
            return jtt.update(po);
        } catch (Exception e) {
            throw new DataAccessException("更新数据出错", e);
        }
    }

    /**
     * 更新数据
     * @param po
     * @return
     */
    public static int updateNotNull(Object po) {
        try {
            return jtt.updateNotNull(po);
        } catch (Exception e) {
            throw new DataAccessException("更新数据出错", e);
        }
    }

    /**
     * 新增或更新数据
     * @param po
     * @return
     */
    public static int save(Object po) {
        try {
            return jtt.save(po);
        } catch (Exception e) {
            throw new DataAccessException("保存数据出错", e);
        }
    }

    /**
     * 统计
     * @param sql
     * @param params
     * @return
     */
    public static int count(String sql, Object[] params) {
        return jtt.count(sql, params);
    }


}
